import glob
import os

from data_process.DatasetGenerator import *

class TestDatasetGenerator(DatasetGenerator):
    def __init__(self, params):
        super(TestDatasetGenerator, self).__init__(params)
        self.testPath = 'dataset/only_test.txt'
        self.testType = params.testType
        self.testDealStr = params.testDealStr

    def getTestPathFileFromPath(self, path):
        with open(self.testPath, 'w') as f:
            f.write(f'{path}')

    def getTestPathFileFromDir(self, dirPath):
        pattern = '*.wav'
        search = os.path.join(dirPath, pattern)
        file = open(self.testPath, 'w')
        for path in glob.glob(search):
            path = path.replace(os.sep, '/')
            file.write(f'{path}\n')
        file.close()

    def getTestPathFileFromOtherFile(self, filePath):
        file = open(self.testPath, 'w')
        allPath = readDataFromFile(filePath)
        for path in allPath:
            file.write(f'{path}\n')
        file.close()

    def normalize(self, feature):
        n = feature.shape[0]
        c = feature.shape[1]
        for i in range(n):
            for j in range(c):
                curMax = np.max(feature[i][j])
                curMin = np.min(feature[i][j])
                feature[i][j] = (feature[i][j] - curMin) / (curMax - curMin)
        return feature


    def emsembleProcess(self):
        if self.testType == 'single':
            self.getTestPathFileFromPath(self.testDealStr)
        elif self.testType == 'path_file':
            self.getTestPathFileFromOtherFile(self.testDealStr)
        elif self.testType == 'dir':
            self.getTestPathFileFromDir(self.testDealStr)
        else:
            raise ValueError
        testData = self.processData(self.testPath)

        self.testAllMin = self.getAllLimit(testData[0], 'min')
        self.testAllMax = self.getAllLimit(testData[0], 'max')

        testData[0] = self.padDataAndTranspose(testData[0])
        testData[0] = self.normalize(testData[0])

        print(testData[0].shape)

        testSavePath = "dataset/only_test.dp"
        self.saveData(testData, testSavePath)

